<script setup>
import {
    Edit,
    Delete
} from '@element-plus/icons-vue'
import { ref } from 'vue'
import { ElMessage , ElMessageBox} from 'element-plus'
import { Download , Upload} from '@element-plus/icons-vue'

const services = ref([{
    "serId": '',
    "userId": '',
    "userName": '',
    "phone": '',
    "style": '',
    "status": ''
}])

const servicesModel = ref({
    serId: '',
    userId: '',
    userName: '',
    phone: '',
    style: '',
    status: ''
})

const servicesSearchModel = ref({
    style: '',
    status: '',
    userId: ''
})

// 业务类型下拉选项
const styleOptions = ref([
  { label: '销售管理', value: '销售管理' },
  { label: '售后服务', value: '售后服务' },
  { label: '市场营销', value: '市场营销' },
  { label: '客服服务', value: '客服服务' }
]);

//业务状态下拉选项
const statusOptions = ref([
  { label: '处理中', value: '处理中' },
  { label: '已完成', value: '已完成' }
]);

//校验
const rules = ref({
    style:[{required: true, message:"业务类型不能为空", trigger:'blur'}],
    userId:[{required: true, message:"客户编号不能为空", trigger:'blur'}],
    status:[{required: true, message:"业务状态不能为空", trigger:'blur'}]
})

//控制标题显示
const title = ref('');
//控制添加业务弹窗
const dialogVisible = ref(false);

import { workServicesListService , workServicesAddService , workServicesDeleteService , workServicesUpdateService , workServicesSearchService , exportServicesExcelService , importServicesExcelService} from '@/api/work'

//调用查询接口
const workServicesList = async()=>{
    let result = await workServicesListService();
    services.value = result.data;
}
workServicesList();

//调用添加接口
const workServicesAdd = async()=>{
    let result = await workServicesAddService(servicesModel.value);
    if(result.code === 0){
        ElMessage.success("添加成功");
    }
    else{
        ElMessage.error("添加失败");
    }
    workServicesList();
    dialogVisible.value = false;
}

//调用删除接口
const workServicesDelete = async(row)=>{
    ElMessageBox.confirm(
        '你确定要删除该业务信息吗?',
        '温馨提示',
        {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        }
    )
        .then(async () => {
            let result = await workServicesDeleteService(row.serId);
            ElMessage({
                type: 'success',
                message: '删除成功',
            })
            workServicesList();
            })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '用户取消删除',
            })
        })
}

//编辑弹窗
const showUpdate = async(row)=>{
    dialogVisible.value = true;
    title.value = "编辑业务信息";

    servicesModel.value.serId = row.serId;
    servicesModel.value.style = row.style;
    servicesModel.value.userId = row.userId;
    servicesModel.value.status = row.status;
}

//调用修改接口
const workServicesUpdate = async()=>{
    let result = await workServicesUpdateService(servicesModel.value);
    if(result.code === 0){
        ElMessage.success('修改成功');
    }else{
        ElMessage.error("修改失败");
    }
    await workServicesList();
    dialogVisible.value = false;
}

//清除数据
const clearData = ()=>{
    servicesModel.value = {
        serId: '',
        userId: '',
        userName: '',
        phone: '',
        style: '',
        status: ''
    }
}

//调用条件查询接口
const search = async()=>{
    const SearchParams = {
        style: servicesSearchModel.value.style,
        status: servicesSearchModel.value.status,
        userId: servicesSearchModel.value.userId
    };
    try{
        let result = await workServicesSearchService(SearchParams);
        services.value = result.data || [];
        if(services.value.length === 0){
            ElMessage.info("未找到匹配的数据");
        }
    }catch(error){
        ElMessage.error('搜索失败：' + error.message);
    }
}

//重置
const restForm = ()=>{
    servicesSearchModel.value.style = '';
    servicesSearchModel.value.status = '';
    servicesSearchModel.value.userId = '';
    workServicesList();
}

//调用导出接口
const handleExport = async()=>{
    try{
        const response = await exportServicesExcelService();
        const blob = new Blob([response], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = '业务信息表.xlsx';
        link.click();
        window.URL.revokeObjectURL(url) //释放
        ElMessage.success('导出成功');
    }catch(error){
        ElMessage.error('导出失败' + error.message);
    }
}


const importFile = ref(null);   //定义响应式变量存储选择的文件
//处理文件选择
const handleFileChange = async(file)=>{
    importFile.value = file.raw;   //保存选择的文件
    handleImport();
}

//调用导入接口
const handleImport = async()=>{
    if(!importFile.value){
        ElMessage.warning('请选择要导入的文件');
        return;
    }
    try{
        let result = await importServicesExcelService(importFile.value);
        if(result.code === 0){
            ElMessage.success('导入成功')
            await workServicesList();
        }else{
            ElMessage.error('导入失败');
        }
    }catch(error){
        ElMessage.error('导入错误:' + error.message);
    }
}
</script>
<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>业务管理</span>
                <div class="extra">
                    <el-button type="primary" @click="dialogVisible=true; title='添加业务'; clearData()">添加业务</el-button>
                    <el-upload
                        class="upload-btn"
                        action="#" 
                        :auto-upload="false" 
                        :on-change="handleFileChange" 
                        :show-file-list="true" >
                    <el-button type="success" @click="handleImport"><el-icon><Upload /></el-icon> 导入业务信息</el-button>
                    </el-upload>
                    <el-button type="success" @click="handleExport"><el-icon><Download /></el-icon> 导出业务信息</el-button>
                </div>
            </div>
        </template>
        <!-- 搜索表单 -->
        <el-form inline :model="servicesSearchModel">
            <el-form-item label="业务类型：" prop="style">
                <el-select v-model="servicesSearchModel.style" placeholder="请选择业务类型" clearable style="width: 200px">
                <el-option v-for="(item, index) in styleOptions" :key="index" :label="item.label" :value="item.value"></el-option>
                </el-select>  
            </el-form-item>
            <el-form-item label="业务状态：" prop="status">
                <el-select v-model="servicesSearchModel.status" placeholder="请选择业务状态" clearable style="width: 200px">
                <el-option v-for="(item, index) in statusOptions" :key="index" :label="item.label" :value="item.value"></el-option>
                </el-select>  
            </el-form-item>
            <el-form-item label="客户编号：" prop="userId">
                <el-input v-model="servicesSearchModel.userId" placeholder="请输入客户编号"></el-input>
            </el-form-item>
            
            <el-form-item>
                <el-button type="primary" @click="search">搜索</el-button>
                <el-button @click="restForm">重置</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="services" style="width: 100%">
            <el-table-column label="序号" width="100" type="index"> </el-table-column>
            <el-table-column label="业务编号" prop="serId"></el-table-column>
            <el-table-column label="业务类型" prop="style"></el-table-column>
            <el-table-column label="客户名" prop="userName"></el-table-column>
            <el-table-column label="手机号" prop="phone"></el-table-column>
            <el-table-column label="状态" prop="status"></el-table-column>
            <el-table-column label="操作" width="100">
                <template #default ="{row}">
                    <el-button :icon="Edit" circle plain type="primary" @click="showUpdate(row)"></el-button>
                    <el-button :icon="Delete" circle plain type="danger" @click="workServicesDelete(row)"></el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <!-- 添加分类弹窗 -->
        <el-dialog v-model="dialogVisible" :title="title" width="30%">
            <el-form :model="servicesModel" :rules="rules" label-width="100px" style="padding-right: 30px">
                <el-form-item label="业务类型" prop="style">
                    <el-select v-model="servicesModel.style" placeholder="请选择业务类型" clearable>
                    <el-option v-for="(item, index) in styleOptions" :key="index" :label="item.label" :value="item.value"></el-option>
                    </el-select> 
                </el-form-item>
                <el-form-item label="客户编号" prop="userId">
                    <el-input v-model="servicesModel.userId" minlength="1" maxlength="10"></el-input>
                </el-form-item>
                <el-form-item label="业务状态：" prop="status">
                    <el-select v-model="servicesModel.status" placeholder="请选择业务状态" clearable style="width: 200px">
                    <el-option v-for="(item, index) in statusOptions" :key="index" :label="item.label" :value="item.value"></el-option>
                    </el-select>  
                </el-form-item>
            </el-form>
            <template #footer>
             <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="title==='添加业务'? workServicesAdd(): workServicesUpdate()"> 确认 </el-button>
                </span>
            </template>
        </el-dialog>
    </el-card>
</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
    .header .extra {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .upload-btn {
            display: inline-flex;
            align-items: center;
        }
}
</style>